import moment from "moment";
import {remote} from 'electron';
import fs from 'fs';
import path from 'path';
import {configStore} from "@/store/config"

let storeConfig = configStore();

/**
 * 保存文件
 * @param filename
 * @param content
 */
export function saveFile(filename, content) {
	const filePath = path.join(remote.app.getPath('documents'), filename);
	try {
		fs.writeFileSync(filePath, content, 'utf8');
		console.log('File saved successfully!');
	} catch (err) {
		console.error('Error saving file:', err);
	}
}
export function readFile(filename) {
	const filePath = path.join(remote.app.getPath('documents'), filename);
	return fs.readFileSync(filePath, 'utf8');
}

/**
 * 格式化时间
 * @param timestamp
 * @param format
 * @returns {string}
 */
export function formatTime(timestamp, format = 'YYYY-MM-DD HH:mm') {
	return moment(timestamp|| (+new Date())).format(format);
}

export function formatHttpUrl(domain = "") {
	let url = domain.replace("http://", "").replace("https://","");
	url  = url.split("/");
	return "https://" + url[0];
}

/**
 * 去头尾空格
 * @param str
 * @returns {*}
 */
export function trim(str) {
	return str.replace(/^\s+|\s+$/g, "");
}

/**
 * 格式化水盘
 * @param ratio
 * @returns {number}
 */
export function formatRECount(ratio) {
	ratio += "";
	ratio = ratio.split("/");
	if(ratio.length === 2) {
		ratio = ((trim(ratio[0]) * 1) + (trim(ratio[1]) * 1))/2;
	}else {
		ratio = ratio[0] * 1;
	}
	ratio = ratio.toFixed(2);
	return ratio * 1;
}


/**
 * 同步延迟，默认0.2秒
 * @param time
 * @returns {Promise<unknown>}
 */
let delayTime;
export function delay(time) {
	// delayTime && clearTimeout(delayTime);
	// delayTime = null;
	return new Promise(function (resolve) {
		setTimeout(resolve, time||200);
	});
}

/**
 * 处理时间格式
 * @param {string} timeString
 * @returns {number}
 */
export function formatHgaTime(timeString) {
	// 获取当前年份
	const currentYear = new Date().getFullYear();
	const timeStr = timeString.slice(0, -1);
	const datetime = `${currentYear}-${timeStr}`;
	const timestamp = new Date(datetime).getTime() / 1000;
	const dateTime = new Date(datetime);

	// 根据后缀进行小时的调整
	const suffix = timeString.slice(-1);
	if (suffix === 'p') {
		const timeTemp = timeString.split(" ")[1].replace("p", "");
		if (timeTemp >= "12:00" && timeTemp <= "12:59") {
			dateTime.setHours(dateTime.getHours() + 12);
		} else {
			dateTime.setHours(dateTime.getHours() + 24);
		}
	} else if (suffix === 'a') {
		dateTime.setHours(dateTime.getHours() + 12);
	}
	// 返回时间戳
	return Math.floor(dateTime.getTime());
}

export function utf16to8(str) {
	var out, i, len, c;
	out = "";
	len = str.length;
	for(i = 0; i < len; i++) {
		c = str.charCodeAt(i);
		if ((c >= 0x0001) && (c <= 0x007F)) {
			out += str.charAt(i);
		} else if (c > 0x07FF) {
			out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
			out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
			out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		} else {
			out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
			out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		}
	}
	return out;
}

/**
 * 过滤名字内容
 * @param itemName
 * @returns {string}
 */
export function replaceTeamName(itemName = ''){
	itemName = itemName.replaceAll(" U","U");
	itemName = itemName.replaceAll("'","");
	itemName = itemName.replaceAll("II ","II");
	itemName = itemName.replaceAll(" (","(");
	return itemName;
}

/**
 * 关联比赛列表
 * @param ps_list
 * @param hga_list
 * @param guanList
 */
export function nameGuanTeam(ps_list = [], hga_list = []) {
	let hga_config_list = {};

	let hga_ps_config = {};

	hga_list.forEach((item) => {
		let competition = item['competition'];
		let one_key = `${competition['time_str']}_${competition['team_h']}`;
		let one_key2 = `${competition['time_str']}_${competition['team_c']}`;
		hga_config_list[one_key] = item;
		hga_config_list[one_key2] = item;
	})

	ps_list.forEach((item) => {
		let competition = item['competition'];
		let team_h_list = storeConfig.nameGuanList[competition['team_h']]||"";
		let team_c_list = storeConfig.nameGuanList[competition['team_c']]||"";

		if(team_h_list) {
			team_h_list = team_h_list.split(",");
		}else {
			team_h_list = [];
		}
		if(team_c_list) {
			team_c_list = team_c_list.split(",");
		}else {
			team_c_list = [];
		}
		team_h_list.forEach((team_name) => {
			let one_key = `${competition['time_str']}_${team_name}`;
			if(hga_config_list[one_key]) {
				hga_ps_config[one_key] = `${competition['time_str']}_${competition['team_h']}`;
			}
		})
		team_c_list.forEach((team_name) => {
			let one_key = `${competition['time_str']}_${team_name}`;
			if(hga_config_list[one_key]) {
				hga_ps_config[one_key] = `${competition['time_str']}_${competition['team_c']}`;
			}
		})
		// console.log(['team', competition['team_h'], team_h_list, competition['team_c'],team_c_list]);
	})
	return hga_ps_config;
}

/**
 * 根据配置获取不同域名
 */
export function getDomainUrl() {
	let HOST = process.env.NODE_ENV === 'development' ? "5.uwigb.mynatapp.cc" : "tdc.w115.net";
	if(process.env.DOMAIN_URL === 'dd') {
		HOST = "dd.w115.net";
	}
	return HOST;
}